package com.feidee.data.report.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;

import com.feidee.data.report.constant.Constant;
import com.feidee.data.report.exception.DataDaoException;
import com.uhb.base.exception.DaoException;


public class JdbcManager {

    /**
     * connect to mysql
     *
     * @throws DaoException
     */
    public static Connection getConnection(Map<String, String> dbInfo) throws DataDaoException {
        String url = dbInfo.get(Constant.MYSQL_URL);
        String user = dbInfo.get(Constant.MYSQL_USER);
        String password = dbInfo.get(Constant.MYSQL_PASSWORD);
        String driverClass = dbInfo.get(Constant.MYSQL_JAVA_DRIVER_CLASS);
        try {
            Class.forName(driverClass);
            return DriverManager.getConnection(url, user, password);
        } catch (ClassNotFoundException e) {
            throw new DataDaoException("Database connection failed", e);
        } catch (SQLException e) {
            throw new DataDaoException("Database connection failed", e);
        }
    }
    
    public static Connection getConnection(String driver,String connUrl,String username,String pwd) throws DataDaoException {
            try {
                Class.forName(driver);
                return DriverManager.getConnection(connUrl, username, pwd);
            } catch (ClassNotFoundException e) {
                throw new DataDaoException("Database connection failed 1", e);
            } catch (SQLException e) {
                throw new DataDaoException("Database connection failed 2", e);
            }
    }
    
    public static void destroy(Connection conn, Statement stmt, ResultSet rs) throws DataDaoException {

        try {
            if (null != rs) {
                rs.close();
            }
            if (null != stmt) {
                stmt.close();
            }
            if (null != conn) {
                conn.close();
            }
        } catch (Exception e) {
            throw new DataDaoException(e.getMessage(),e);
        }
    }
}
